package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.IngredientDAOImpl;
import edu.cmu.cs.webapp.ioms.dao.impl.ProductDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Ingredient;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.ui.wizards.ingredient.IngredientWizard;
import edu.cmu.cs.webapp.ioms.ui.wizards.product.ProductWizard;
import edu.cmu.cs.webapp.ioms.views.CustomersListView;
import edu.cmu.cs.webapp.ioms.views.IngredientInfoView;
import edu.cmu.cs.webapp.ioms.views.IngredientListView;
import edu.cmu.cs.webapp.ioms.views.OrderDetailsView;

public class NewIngredientViewAction implements IViewActionDelegate {

	private IngredientInfoView _view;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		this._view = (IngredientInfoView) view;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		IngredientWizard wizard = new IngredientWizard(false, null);
		wizard.setWindowTitle("Add a new ingredient");
		WizardDialog dialog = new WizardDialog(_view.getViewSite().getShell(),
				wizard);
		dialog.setBlockOnOpen(true);
		dialog.open();

		int returnCode = dialog.getReturnCode();

		if (returnCode == org.eclipse.jface.window.Window.OK) {
			// create new order
			Ingredient ing = wizard.getModel();

			try {
				new IngredientDAOImpl().addIng(ing);
				
				this._view.refreshIngredientsView();
				IngredientListView.getFormulaListViewPart(
						this._view.getViewSite()).refIngrListView();
			} catch (DataAccessException e) {
				e.printStackTrace();
			}
		}

		// important but currently of no uses
		/*
		 * CustomersListView.getCustomersListViewPart(this._view.getViewSite())
		 * .refreshCustomersView();
		 */
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
